#include "EyerWASMHttp.hpp"

#include "EyerWASMEventXMLHttpRequest.hpp"
#include "EyerWASMCommon/EyerWASMEventLoop.hpp"
#include "EyerWASMHttpFetch_AbortEvent.hpp"

namespace Eyer
{
    EyerWASMHttp::EyerWASMHttp(const std::string & _url, int64_t _rangeStart, int64_t _rangeEnd)
        : url(_url)
        , rangeStart(_rangeStart)
        , rangeEnd(_rangeEnd)
    {
        event = std::make_shared<EyerWASMHttpFetch_FetchEvent>(url, rangeStart, rangeEnd);
    }

    EyerWASMHttp::~EyerWASMHttp()
    {

    }

    int EyerWASMHttp::Send()
    {
        std::unique_lock<std::mutex> lck(event->mtx);
        EyerWASMEventLoop::GetInstance()->PutEvent(event);
        return 0;
    }

    int EyerWASMHttp::WaitHttpHeader()
    {
        std::unique_lock<std::mutex> lck(event->mtx);
        while(!event->isHttpHeaderRecved()){
            event->cond.wait_for(lck, std::chrono::seconds(1));
        }
        return 0;
    }

    int EyerWASMHttp::WaitHttpBody()
    {
        std::unique_lock<std::mutex> lck(event->mtx);
        while(!event->isFinish()){
            event->cond.wait_for(lck, std::chrono::seconds(1));
        }
        return 0;
    }

    int EyerWASMHttp::Abort()
    {
        int fetchAbortKey = event->GetFetchAbortKey();
        std::shared_ptr<EyerWASMHttpFetch_AbortEvent> abortEvent = std::make_shared<EyerWASMHttpFetch_AbortEvent>(fetchAbortKey);
        EyerWASMEventLoop::GetInstance()->PutEvent(abortEvent);

        std::unique_lock<std::mutex> lck(event->mtx);
        while(!event->isFinish()){
            event->cond.wait_for(lck, std::chrono::seconds(1));
        }
        return 0;
    }


    int EyerWASMHttp::GetHttpStatus()
    {
        return event->GetHttpStatus();
    }

    int EyerWASMHttp::GetBufferLen()
    {
        return event->GetBufferSize();
    }

    uint8_t * EyerWASMHttp::GetBuffer()
    {
        return event->GetBufferPtr();
    }

    int64_t EyerWASMHttp::GetContentLength()
    {
        return event->GetContentLength();
    }

    int64_t EyerWASMHttp::GetRangeLength()
    {
        return event->GetRangeLength();
    }
}